/**    
 * @Title: HttpController.java  
 * @Package cn.com.ytst.data.integration.controller  
 * @Description: 
 * @author yanhewei@vv.cc.com    
 * @date 2019年5月3日 下午8:24:35  
 * @version V1.0    
*/
package cn.com.ytst.data.integration.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;


import com.ytst.framework.common.StringTools;

import cn.com.ytst.data.integration.CommonKey;
import cn.com.ytst.data.integration.manager.job.QuartzManager;
import cn.com.ytst.data.integration.util.PageUtil;
import cn.com.ytst.data.integration.util.filter.FileFilter;
import cn.com.ytst.data.integration.vo.AjaxResult;
import cn.com.ytst.data.integration.vo.DataTable;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.datax.common.util.Configuration;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

import com.google.common.collect.Maps;


/**
 * @ClassName: HttpController
 * @Description: 
 * @author yanhewei@vv.cc.com
 * @date 2019年5月3日 下午8:24:35
 * 
 */
@Controller
@RequestMapping
public class HttpController {

	 @Value("${filepath}")
	 private String filepath;

	
	@Autowired
	private QuartzManager quartzManager;


	
	@RequestMapping(value = "/http/grid", method = RequestMethod.POST)
	@ResponseBody
	public DataTable<JSONObject> grid(HttpServletRequest request) throws IOException {
		String pageNumber = StringTools.isBlank(request.getParameter("pageNum"))?"1":request.getParameter("pageNum");
		String pageSize =  StringTools.isBlank(request.getParameter("pageSize")) ? "10":request.getParameter("pageSize");
		List<File> list = FileFilter.fiterFile(filepath+File.separator+"http", "http");
		List<JSONObject> list_json = Lists.newArrayList();
		if (!list.isEmpty()) {
			for (File f : list) {
				JSONObject jsonObject = new JSONObject();
				Configuration configuration = Configuration.from(FileUtils.readFileToString(f, "utf-8"));
				String url = configuration.getString(CommonKey.HTTP_URL);
				String method = configuration.getString(CommonKey.HTTP_METHOD);
				String name = configuration.getString(CommonKey.HTTP_NAME_TAG);
				String sysName = configuration.getString(CommonKey.HTTP_SYSNAME);
				String parameters = configuration.getString(CommonKey.HTTP_PARAMETERS);
				String cronexpress = configuration.getString(CommonKey.HTTP_CORN_TAG);
				jsonObject.put("name", name);
				jsonObject.put("url", url);
				jsonObject.put("parameters", parameters);
				jsonObject.put("methodtype", method);
				jsonObject.put("sysname", sysName);
				jsonObject.put("id", f.getName());
				jsonObject.put("cronexpress", cronexpress);
				list_json.add(jsonObject);

			}
		}
		DataTable<JSONObject> dataTable = new DataTable<>();
		dataTable.setRows(PageUtil.startPage(list_json,Integer.parseInt(pageNumber),Integer.parseInt(pageSize)));
		dataTable.setTotal(list_json.size());
		dataTable.setCode(0);
		dataTable.setMsg("");
		return dataTable;

	}

	@RequestMapping(value = "/http/add", method = RequestMethod.GET)
	public String add() {
		return "/page/component/http/http-add";
	}
	
	@RequestMapping(value="/http/save",method= RequestMethod.POST)
    @ResponseBody
    public AjaxResult save(HttpServletRequest request) {
    	String name = request.getParameter("name");
    	String syncType = request.getParameter("syncType");
    	String methodtype = request.getParameter("methodtype");
    	String is_batch = request.getParameter("is_batch");
    	String formtype = request.getParameter("formtype");
    	String url = request.getParameter("url");
    	String sysname = request.getParameter("sysname");
    	String corn = request.getParameter("corn");
    	String parameters = request.getParameter("parameters");
    	String table_name = request.getParameter("table_name");
    	File file = new File(filepath+File.separator+"http"+File.separator+"http_"+sysname.toLowerCase()+".json");
    	try {
    		 String str = FileUtils.readFileToString(new File(filepath+File.separator+"temp"+File.separator+"http_temp.json"),"utf-8");
			 FileUtils.write(file, str, "utf-8");//先预先创建一个文件
			 Configuration configuration = Configuration.from(file);
			 configuration.set(CommonKey.HTTP_IS_BATCH, Integer.parseInt(is_batch) == 2 ? true:false);
			 configuration.set(CommonKey.HTTP_SYSNAME, sysname);
			 configuration.set(CommonKey.HTTP_PAGESIZE, 100+"");

			 configuration.set(CommonKey.HTTP_NAME_TAG, name);
             configuration.set(CommonKey.HTTP_FORM_FRAMTE, formtype);
			 Map<String,String> prarms = Maps.newHashMap(); 
			 //如果存在多个的话，需要用逗号隔开例如key:value,key1:value1
			 if(!Strings.isBlank(parameters)) {
				 String [] keyvalues = parameters.split(",");
				 for(String kv : keyvalues) {
					 String [] parameters_1 =  kv.split(":");
					 prarms.put(parameters_1[0], parameters_1[1]);
				 }
				 configuration.set(CommonKey.HTTP_PARAMETERS+".parameter[0]",prarms); //这个地方用list<Map<String,String>>
			 }else {
				 configuration.set(CommonKey.HTTP_PARAMETERS+".parameter[0]",prarms); //这个地方用list<Map<String,String>>
			 }
			 configuration.set(CommonKey.HTTP_SYNC_TYPE, syncType);
			 configuration.set(CommonKey.HTTP_TABLE_NAME,table_name);
			 configuration.set(CommonKey.HTTP_METHOD,methodtype);
			 configuration.set(CommonKey.HTTP_URL, url);
			 configuration.set(CommonKey.HTTP_CORN_TAG,corn);
			 String json = configuration.beautify();
			 FileUtils.write(file, json, "utf-8");//先预先创建一个文件
			 return AjaxResult.success(sysname+"添加成功!");
		} catch (IOException e) {
			e.printStackTrace();
		}
    	 return AjaxResult.error(sysname+"添加失败!");

    }
	
	@RequestMapping(value="/http/update",method= RequestMethod.POST)
    @ResponseBody
    public AjaxResult update(HttpServletRequest request) {
    	String name = request.getParameter("name");
    	String id = request.getParameter("id");
    	String syncType = request.getParameter("syncType");
    	String methodtype = request.getParameter("methodtype").toUpperCase();
    	String is_batch = request.getParameter("is_batch");
		String formtype = request.getParameter("formtype");
    	String url = request.getParameter("url");
    	String sysname = request.getParameter("sysname");
    	String corn = request.getParameter("cronexpress");
    	String topic = request.getParameter("topic");
    	String page_size = request.getParameter("page_size");
    	String parameters = request.getParameter("parameters");
    	String table_name = request.getParameter("table_name");
    	File file = new File(filepath+File.separator+"http"+File.separator+id);
    	try {
    		 String str = FileUtils.readFileToString(file,"utf-8");
			 Configuration configuration = Configuration.from(str);
			 configuration.set(CommonKey.HTTP_IS_BATCH, Integer.parseInt(is_batch) == 2 ? true:false);
			 configuration.set(CommonKey.HTTP_SYSNAME, sysname);
			 configuration.set(CommonKey.HTTP_PAGESIZE, page_size);
			 configuration.set(CommonKey.KAFAK_WRITER_TOPIC_TAG, topic);
			configuration.set(CommonKey.HTTP_FORM_FRAMTE, formtype);
			 configuration.set(CommonKey.HTTP_NAME_TAG, name);
			 JSONArray jsonArray = new JSONArray(12);
			
			 //如果存在多个的话，需要用逗号隔开例如key:value,key1:value1
			 if(!Strings.isBlank(parameters)) {
				 String [] keyvalues = parameters.split(",");
				 for(String kv : keyvalues) {
					 JSONObject jsonObject = new JSONObject();
					 String [] parameters_1 =  kv.split(":");
					 if(parameters_1.length <2 ) {
						 jsonObject.put(parameters_1[0], "");
					 }else {
						 jsonObject.put(parameters_1[0], parameters_1[1]);	 
					 }
					 
					 jsonArray.add(jsonObject);
				 }
				 configuration.set(CommonKey.HTTP_PARAMETERS+".parameter",JSON.parse(jsonArray.toString())); //这个地方用list<Map<String,String>>
			 }else {
				 configuration.set(CommonKey.HTTP_PARAMETERS+".parameter",JSON.parse(jsonArray.toString())); //这个地方用list<Map<String,String>>
			 }
			 configuration.set(CommonKey.HTTP_SYNC_TYPE, syncType);
			 configuration.set(CommonKey.HTTP_TABLE_NAME,table_name);
			 configuration.set(CommonKey.HTTP_METHOD,methodtype);
			 configuration.set(CommonKey.HTTP_URL, url);
			 configuration.set(CommonKey.HTTP_CORN_TAG,corn);
			 String json = configuration.beautify();
			 FileUtils.write(file, json, "utf-8");//先预先创建一个文件
			 return AjaxResult.success(sysname+"添加成功!");
		} catch (IOException e) {
			e.printStackTrace();
		}
    	 return AjaxResult.error(sysname+"添加失败!");

    }
	
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/http/edit/{id}",method= RequestMethod.GET)
    public ModelAndView edit( @PathVariable(value = "id") String id) throws IOException {
    	Configuration configuration = Configuration.from(FileUtils.readFileToString(new File(filepath+File.separator+"http"+File.separator+id), "utf-8"));
    	Set<String> set = configuration.getKeys();
    	Map<String,Object> map = Maps.newHashMap();
    	for(String key : set) {
    		int last_index = key.lastIndexOf(".");
    		String end_key = key.substring(last_index+1);
    		if("is_batch".equals(end_key)) {
    			map.put(end_key, (boolean)configuration.get(key) ?"1":"2");
    		}else if("encrypt".equals(end_key)) {
    			map.put(end_key, (boolean)configuration.get(key) ?"1":"2");
    		}else {
    			map.put(end_key, configuration.get(key));
    		}
    		
    	}
    	StringBuffer sb = new StringBuffer(32);
    	//参数
    	map.put("id", id);
    	JSONArray jsonArray =	(JSONArray)JSONArray.parse(configuration.getString("job.content[0].reader.parameters.parameter"));
    	if(null != jsonArray) {
    	   for(Object ob : jsonArray) {
    		   Map<String,String> prarms = JSONObject.parseObject(ob.toString(), Map.class) ;
    		   for(Map.Entry<String, String> entry : prarms.entrySet()) {
    			   String key = entry.getKey();
    			   String value = entry.getValue();
    			   sb.append(key).append(":").append(value).append(",");
    		   }
    	   }	
    	}
    	map.put("parameters",sb.indexOf(",")> -1 ? sb.subSequence(0, sb.lastIndexOf(",")).toString():"");
    	return  new ModelAndView("/page/component/http/http-edit",map);
    }
	
	
//	@RequestMapping(value="/http/start",method= RequestMethod.POST)
//    @ResponseBody
//    public AjaxResult start(String id) {
//    	try {
//    		File file = new File(filepath+File.separator+"http"+File.separator+id);
//    		Configuration configuration = Configuration.from(file);
//    		String name = configuration.getString(CommonKey.HTTP_NAME_TAG);
//    		String cronexpress = configuration.getString(CommonKey.HTTP_CORN_TAG);
//    		quartzManager.addTask(name, name, QuartzJobFactoryDisallowConcurrentExecution.class, cronexpress, "engin", httpengine, filepath+"/http/"+id);
//    		quartzManager.taskStart();
//			return AjaxResult.success(id+"任务启动成功!");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//    	 return AjaxResult.error(id+"任务启动失败!");
//
//    }
//
//
//    @RequestMapping(value="/http/stop",method= RequestMethod.POST)
//    @ResponseBody
//    public AjaxResult stop(String id) {
//    	try {
//    		File file = new File(filepath+File.separator+"http"+File.separator+id);
//    		Configuration configuration = Configuration.from(file);
//    		String name = configuration.getString(CommonKey.HTTP_NAME_TAG);
//    		TaskManager task = new TaskManager();
//    		task.setJobName(name);
//    		task.setGroupName(TaskManager.GROUP_NAME);
//    		quartzManager.pauseTask(task);
//			 return AjaxResult.success(id+"任务停止成功!");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//    	 return AjaxResult.error(id+"任务停止失败!");
//
//    }


    @RequestMapping(value="/http/remove",method= RequestMethod.POST)
    @ResponseBody
    public AjaxResult delete(String ids){
        try {
            File f = new File(filepath+File.separator+"http"+File.separator+ids);
            FileUtils.forceDelete(f);
            return AjaxResult.success(ids+"删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error(ids+"删除失败!");
    }
    
    
}
